import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-08-02
 * Time:20:24
 */
class Message {
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    // 用于保存所有的留言
//    private List<Message> messages = new ArrayList<>();
    // 用于转换JSON字符串
    private ObjectMapper objectMapper = new ObjectMapper();
//    数据文件路径
    private String filePath = "e:/messages.txt";

//    public List<Message> load() {
//        List<Message> messages = new ArrayList<>();
//        System.out.println("从文件读取数据");
//        try (BufferedReader bufferedReader =
//                     new BufferedReader(new FileReader(filePath))) {
//            while(true) {
//                String line = bufferedReader.readLine();
//                if (line == null) {
//                    break;
//                }
//                String[] tokens = line.split("\t");
//                Message message = new Message();
//                message.from = tokens[0];
//                message.to = tokens[1];
//                message.message = tokens[2];
//                messages.add(message);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println("共读取数据 " + messages.size() + " 条！");
//        return messages;
//    }

//    数据库版load方法
    public List<Message> load() {
        List<Message> messages = new ArrayList<>();
//        和数据库建立连接
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
//            拼接SQL
            String sql = "select * from messages";
            statement = connection.prepareStatement(sql);
//            执行SQL
            resultSet = statement.executeQuery();
//            遍历结果集合
            while (resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messages.add(message);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
//            释放资源
            DBUtil.close(connection, statement, resultSet);
        }
        return messages;
    }

    public void save(Message message) {
//        建立连接
        Connection connection = DBUtil.getConnection();
        PreparedStatement statement = null;
        try {
//            拼装SQL
            String sql = "insert into messages values(?, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
//            执行SQL
            statement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
//            释放资源
            DBUtil.close(connection, statement, null);
        }
    }

//    public void save(Message message) {
//        System.out.println("向文件写入数据");
////        使用追加写的方式打开文件
//        try (FileWriter fileWriter = new FileWriter(filePath, true)) {
//            fileWriter.write(message.from + "\t" + message.to + "\t" +
//                    message.message + "\n");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    // 获取所有留言
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        List<Message> messages = load();
//        只需要把消息列表中的内容整个返回给客户端即可
//        使用objectMapper把java对象转换成JSON格式字符串
        String respString = objectMapper.writeValueAsString(messages);
        System.out.println("respString: " + respString);
        resp.getWriter().write(respString);
    }

    // 新增留言
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
//        保存到内存中
//        messages.add(message);
        save(message);
        resp.getWriter().write("{\"ok\":true}");
    }
}
